package mc.contents.web.servlet;
import mc.contents.dao.ShopInfoMapper;
import mc.contents.pojo.persistence.ShopInfo;
import mc.contents.etc.CrawHandler;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by LuoHui on 14-11-26.
 */
@WebServlet(name = "shopUrlResponse",urlPatterns="/shopUrlResponse",asyncSupported=false)
public class ShopUrlResponseServlet extends HttpServlet {
    private static Logger log = LoggerFactory.getLogger( ShopUrlResponseServlet.class );
    private ShopInfoMapper shopInfoMapper;
    private CrawHandler crawHandler;


    @Override
    public void init( ServletConfig config ) throws ServletException {
        super.init( config );
        ServletContext servletContext = config.getServletContext();
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext( servletContext );
        shopInfoMapper = (ShopInfoMapper) context.getBean( "shopInfoMapper" );
        crawHandler = (CrawHandler) context.getBean( "crawHandler" );
    }

    @Override
    protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
        try{
            String nick = req.getParameter( "nick" );
            String shopUrl = req.getParameter( "shopUrl" );
            if(StringUtils.isNotEmpty( nick ) && StringUtils.isNotEmpty( shopUrl ) && !"undefined".equals( shopUrl )){
                log.info("{} get shop url {}",nick,shopUrl);
                ShopInfo shopInfo = new ShopInfo();
                shopInfo.setNick(nick);
                shopInfo.setShopUrl( shopUrl );
                shopInfoMapper.saveShopUrl( shopInfo );

                //dsr
                if(shopInfo.getShopUrl()!=null){
                    crawHandler.crawDsr(shopInfo);
                    crawHandler.crawShop4C( shopInfo );
                }
            }
        }catch ( Exception e ){
            e.printStackTrace();
        }
    }
}
